package com.share.PACManager.task;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.share.PACManager.model.CompanyModel;
import com.share.PACManager.model.CompanyPersonModel;
import com.share.PACManager.model.FreePersonModel;
import com.share.PACManager.model.LeasePersonModel;
import com.share.PACManager.model.PersonModel;
import com.share.PACManager.model.TerminalModel;
import com.share.PACManager.net.HTTPResponse;
import com.share.PACManager.net.HttpUtility;
import com.share.PACManager.utils.Cryptography;
import com.share.PACManager.utils.Utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;


public class GetPersonsTask extends Thread{

	private GetPersonsListener mListener;
	private Context mContext;
	
	private TerminalModel mTerminal;
	private List<PersonModel> mPersons;
	private List<CompanyModel> mCompanies;
	
	public interface GetPersonsListener {
		public TerminalModel requestTerminal();
		public List<CompanyModel> requestCompanies();
		public void onCheckResult(boolean result, List<PersonModel> list);
	}

	public GetPersonsTask(Context context) {
		mContext = context;
	}
	
	public void start(GetPersonsListener listener) {
		mListener = listener;
		if(mListener != null)
		{
			mTerminal = mListener.requestTerminal();
			mCompanies = mListener.requestCompanies();
			start();
		}
	}

	private Handler handler = new Handler(){		
		@Override
		public void handleMessage(Message msg)
		{
			if(mListener != null)
			{
				if(msg.what == 0)
					mListener.onCheckResult(false, mPersons);
				else
				{
					HTTPResponse resp = (HTTPResponse) msg.obj;
					if(msg.what == 1)
						parse(resp.content);
					else
						mListener.onCheckResult(mPersons!=null, mPersons);								
				}
			}
		}
	};
	
    public boolean parse(String json)
    {    	
		try {
			JSONObject jsonObject = new JSONObject(json);
			if(!jsonObject.getBoolean("Success"))
				return false;
			
			JSONArray state = jsonObject.getJSONArray("State"); 
			if(state != null)
			{
				if(mPersons == null)
					mPersons = new ArrayList<PersonModel>();
				
				for(int i = 0 ; i < state.length(); i++)
				{
					JSONObject object = state.getJSONObject(i);		
					
					PersonModel person;
					String companyType = Utils.getJsonString(object, "PersonCompanyType");
					if(companyType.equals("Company"))
					{
						person = new CompanyPersonModel();
						CompanyPersonModel p = (CompanyPersonModel) person;
						p.CheckInTime = Utils.getJsonDate(object, "CheckInTime");
						p.CheckOutTime = Utils.getJsonDate(object,"CheckOutTime");
						p.Office = Utils.getJsonString(object, "Office");
						p.Job = Utils.getJsonString(object, "Job");
					}
					else if(companyType.equals("Lease"))
					{
						person = new LeasePersonModel();
						LeasePersonModel p = (LeasePersonModel) person;
						p.LeaseReason = Utils.getJsonString(object, "LeaseReason");
						p.CheckInTime = Utils.getJsonDate(object,"CheckInTime");
						p.CheckOutTime = Utils.getJsonDate(object,"CheckOutTime");
						p.AutoCheckOut = object.getString("AutoCheckOut");
					}
					else
					{
						person = new FreePersonModel();		
						FreePersonModel p = (FreePersonModel) person;
						p.CheckReason = Utils.getJsonString(object, "CheckReason");
					}
					
		   			person.PersonId = Utils.getJsonString(object, "PersonId");
		   			person.PersonCompanyId = Utils.getJsonString(object, "PersonCompanyId");
		   			person.PersonPoliceId = Utils.getJsonString(object, "PersonPoliceId");
		   			person.PersonTerminalId = Utils.getJsonString(object, "PersonTerminalId");
		   			person.PersonTransactionId = Utils.getJsonString(object, "PersonTransactionId");
		   			person.PersonCompanyType = Utils.getJsonString(object, "PersonCompanyType");
		   			person.PersonCardType = Utils.getJsonString(object, "PersonCardType");
		   			person.PersonCardId = Utils.getJsonString(object, "PersonCardId");
		   			person.PersonName = Utils.getJsonString(object, "PersonName");
		   			person.PersonSex = Utils.getJsonString(object, "PersonSex");
		   			person.PersonNation = Utils.getJsonString(object, "PersonNation");
		   			person.PersonNative = Utils.getJsonString(object, "PersonNative");
		   			person.PersonBirthday = Utils.getJsonString(object, "PersonBirthday");
		   			person.PersonAddress = Utils.getJsonString(object, "PersonAddress");
		   			person.PersonPhoneNumber = Utils.getJsonString(object, "PersonPhoneNumber");
		   			person.PersonEastPoint = Utils.getJsonString(object, "PersonEastPoint");
		   			person.PersonNorthPoint = Utils.getJsonString(object, "PersonNorthPoint");
		   			
		   			person.PersonCardImage = Utils.getJsonString(object, "PersonCardImage");
		   			if("null".equals(person.PersonCardImage))
		   				person.PersonCardImage = "";
		   			
		   			person.PersonRealImage = Utils.getJsonString(object, "PersonRealImage");
		   			if("null".equals(person.PersonRealImage))
		   				person.PersonRealImage = "";
		   			
		   			person.PersonCreateTime = Utils.getJsonDate(object,"PersonCreateTime");
		   			person.PersonChangeTime = Utils.getJsonDate(object,"PersonChangeTime");

		   			person.PersonComment = Utils.getJsonString(object, "PersonComment");
		   			person.PersonStatus = Utils.getJsonString(object, "PersonStatus");
		   			if(person.PersonId.length() == 22)
		   			{		   				
		   				person.PersonDate = person.PersonId.substring(10, 18);
		   				person.PersonIndex = Integer.parseInt(person.PersonId.substring(18, 22));//object.getString("CheckReason");
		   			}		   			
		   			person.PersonUpload = 1;//object.getString("CheckReason");
					mPersons.add(person);
				}				
			}
			return true;			
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return false;
    }
    
	@Override
	public void run() {

		try {

			for(CompanyModel company : mCompanies)
			{
				String terminalId = mTerminal.TerminalId;
				String imei = mTerminal.TerminalCode;
				String password = mTerminal.TerminalPassword;
				String ticket = Cryptography.AES_Encode(imei, terminalId, password);
				
				
				String info =	"PersonCompanyId=" + Utils.URLEncode(company.CompanyId) + "&" +
					"PersonCreateTimeBegin=" + "2000-01-01 00:00:00" +"&"+
					"PersonCreateTimeEnd=" + "2900-01-01 00:00:00";
				if(company.CompanyType.equals("Company"))
					info += "&PersonStatus=OnJob";
				else if(company.CompanyType.equals("Lease"))
					info += "&PersonStatus=CheckIn";
				else
					info += "&PersonStatus=None";
				
				info = Cryptography.AES_Encode(info, terminalId, password);
				String entity = "Information=" + URLEncoder.encode(info);
				
				Map<String, String> params = new TreeMap<String, String>();
				params.put("Id", terminalId);
				params.put("TerminalId", terminalId);
				params.put("DataType", "Data");	
				params.put("Password", password);
				params.put("TerminalCode", imei);
				params.put("Version", "1.0");
				params.put("Ticket", ticket);
				params.put("Objective", "GetPersons");
				
				handler.obtainMessage(1, HttpUtility.httpPost(params, entity)).sendToTarget();
			}
			handler.obtainMessage(2).sendToTarget();
		} catch (Exception e) {
			handler.obtainMessage(0).sendToTarget();
		}
		
		super.run();
	}
}
